package com.lely.service.impl;

import com.lely.dao.UserDao;
import com.lely.entity.Page;
import com.lely.entity.User;
import com.lely.entity.UserRoleVO;
import com.lely.service.UserService;
import java.util.ArrayList;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

/**
 * @author lely
 * @date 2021/4/15 13:46
 */
@Service
public class UserServiceImpl implements UserService {

    @Autowired
    public UserDao userDao;

    @Override
    public User get(Long id) {
        return userDao.get(id);
    }

    @Override
    public List<User> getAll(Page page) {
        if(StringUtils.isEmpty(page.getPageNum())){
            page.setPageNum(1);
        }
        if(StringUtils.isEmpty(page.getPageSize())){
            page.setPageSize(10);
        }
        page.setStart((page.getPageNum()-1)*page.getPageSize());
        return userDao.getAll(page);
    }

    @Override
    public Integer count(String username,String email){
        return userDao.count(username,email);
    }

    @Override
    public Integer add(User user) {
        return userDao.add(user);
    }

    @Override
    public int update(User user) {
        return userDao.update(user);
    }

    @Override
    @Transactional
    public int delete(Long id) {
        //批量删除对应的关联表数据
        userDao.deleteUserRule(id);
        return userDao.delete(id);
    }

    @Override
    public int addUserRole(UserRoleVO vo) {
        List<UserRoleVO> v1 = new ArrayList<>();
        String ids = vo.getRoleIds();
        if(!StringUtils.isEmpty(ids)){
            String[] split = ids.split(",");
            for (int i = 0; i <split.length ; i++) {
                UserRoleVO ur = new UserRoleVO();
                ur.setUserRoleId(System.nanoTime());
                ur.setRoleId(Long.valueOf(split[i]));
                ur.setUserId(Long.valueOf(vo.getUserId()));
                ur.setCreateTime(vo.getCreateTime());
                ur.setUpdateTime(vo.getUpdateTime());
                v1.add(ur);
            }
        }
        return userDao.addUserRole(v1);
    }
}
